#include <sys/types.h>
#include <unistd.h>
#include <sys/vfs.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <stdio.h>
#include "file_mgr.h"
#include "configure.h"
#include "stat.h"

extern struct conf *gconf;
extern struct cache_stat *cache_stat;

void clean_disk(char *disk)
{
	struct statfs buf;
	struct stat f_stat_buf;
	DIR *dir;
	struct dirent *ptr;
	int i, father_dir_len, chi_dir_len;
	father_dir_len=strlen(disk); 
	dir=opendir(disk);
	int del_flag = 0, u = 0;
	while((ptr=readdir(dir))!=NULL){
		while(del_flag ){
			if(statfs(disk,&buf)==0)
				if( (u_int64_t)buf.f_bavail * buf.f_bsize/1024/1024/1024<3) 
					break;
			sleep(10);
		}
		del_flag = 0;
		chi_dir_len=strlen(ptr->d_name);
		i=father_dir_len+chi_dir_len+1;
		char chi_dir_name[i+1];
		chi_dir_name[0]=0;
		strcat(chi_dir_name,disk);
		strcat(chi_dir_name,"/");
		strcat(chi_dir_name,ptr->d_name);

		u = 0;
		if(chi_dir_len == 1 && ptr->d_name[0] == '.') u=1;
		if(chi_dir_len == 2 && *(u_int16_t*)ptr->d_name == *(u_int16_t*)"..") u=1;
		if(u) continue;

		if(ptr->d_type==DT_DIR) {clean_disk(chi_dir_name);}
		else if(ptr->d_type==DT_REG){
			if(stat(chi_dir_name,&f_stat_buf)) continue;

//			stat_lock(cache_stat);
//			cache_stat->check ++;
//			strcpy(cache_stat->lastcheck, chi_dir_name);

			if( time(0)- f_stat_buf.st_atime>gconf->day*24*60*60)
			{
//				cache_stat->clean ++;
//				strcpy(cache_stat->lastclean, chi_dir_name);
//				stat_unlock(cache_stat);
				unlink(chi_dir_name);
				del_flag = 1;
			}else
			{
//				stat_unlock(cache_stat);
			}
		}
	}
	closedir(dir);
}

